package com.ruoyi.framework.support.key;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.siashan.toolkit.lock4j.key.DefaultLockKeyBuilder;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;

/**
 * 防重复提交Key生成器
 *
 * @author siashan
 * @date 2023/6/5
 */
public class MyNotRepeatKeyBuilder extends DefaultLockKeyBuilder {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Override
    public String buildKey(MethodInvocation invocation, String[] definitionKeys) {

        String key = super.buildKey(invocation, definitionKeys);
        // 唯一值（没有消息头则使用请求地址）
        HttpServletRequest request = ServletUtils.getRequest();
        String submitKey = StringUtils.trimToEmpty(request.getHeader(header));
        // 唯一标识（指定key + url + 消息头）
        String cacheRepeatKey = submitKey + ":" + key;

        return cacheRepeatKey;
    }

}
